package com.example.ormsqlsplicingframe1.proxy;

import com.example.ormsqlsplicingframe1.session.SessionUtil;
import com.example.ormsqlsplicingframe1.utlis.ProxySessionUtils;
import com.example.ormsqlsplicingframe1.warpper.UpdateSqlWrapper;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SyncProxyFactory implements IProxyFactory{

    private static ThreadLocal<Map<Object,SyncProxy>>threadLocal = ThreadLocal.withInitial(() -> new HashMap<>());


    private static       Map<Object, SyncProxy> getCache(){
        Map<Object, SyncProxy> cache = threadLocal.get();
        return cache;
    }

    @Override
    public Object getProxy(Object data) {



        if(!ProxySessionUtils.route().isOpenTransaction()){
            throw new RuntimeException("需要开启事务");
        }

        SyncProxy syncProxy = getCache().computeIfAbsent(data, key -> new SyncProxy(data));
        return syncProxy.getProxyInstance();
    }

    public void commitTransaction(){
        Collection<SyncProxy> values = getCache().values();
        List<SyncProxy> collect = values.stream().filter(row -> row.getSize() > 0).collect(Collectors.toList());
        for (SyncProxy proxy : collect) {
            if (UpdateSqlWrapper.newInstance(proxy.getData()).execute() == 0) throw new IllegalStateException("更新失败");
        }
    }

    //获取代理列表
    public List<Object> getProxyList(){
       return getCache().values().stream().collect(Collectors.toList());
    }


    public void rollbackTransaction(){
        getCache().clear();
    }
}
